package app.baseinfomanage.tradedaysmanage;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Calendar;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import app.base.common.Utility;


public class TradeDaysHandle extends HttpServlet {

	private static final long serialVersionUID = 1L;

	public void doGet(HttpServletRequest request, HttpServletResponse response) 
		throws ServletException, IOException 
	{
	    request.setCharacterEncoding(Utility.CHARSET_ENCODING_UTF8);
	    response.setContentType(Utility.DEFAULT_CONTENT_TYPE);

		PrintWriter out = response.getWriter(); 

		String year = request.getParameter("YEAR");
		String month = request.getParameter("MONTH");

		if (year == null || month == null)
		{
			Calendar calendar = Calendar.getInstance(); 
			year = String.valueOf(calendar.get(Calendar.YEAR));   
			month = String.valueOf(calendar.get(Calendar.MONTH) + 1);
			month = month.length() > 1 ? month : "0" + month;
			//date = calendar.get(Calendar.DATE);   
		}
		
		String result = generateTradingDaysOfMonth(Integer.valueOf(year), Integer.valueOf(month), Utility.START_FROM_SATURDAY_FLAGS);
		
		out.println(result);
		
		out.flush();
		out.close();
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response) 
	throws ServletException, IOException 
	{
		doGet(request, response);
	}	
	
	private String generateTradingDaysOfMonth(int year, int month, int format)
	{
		ArrayList<String> al = Utility.generateDaysOfMonth(year, month, format);
		
		//
		
		int totalCount = al.size()/Utility.DAYS_OF_WEEK;
		String json = "{totalProperty:" + totalCount + ",root:[";
		
		for(int index = 0; index < totalCount; index++){

			int idx = index * Utility.DAYS_OF_WEEK;
		
            json += "{Sat:'" + (String)al.get(idx)
            	+ "', Sun:'" + (String)al.get(idx + 1)
            	+ "', Mon:'" + (String)al.get(idx + 2)
            	+ "', tues:'" + (String)al.get(idx + 3)
            	+ "', Wed:'" + (String)al.get(idx + 4)
            	+ "', Thurs:'" + (String)al.get(idx + 5)
            	+ "', Friday:'" + (String)al.get(idx + 6) + "'}";
            
            if (index < totalCount - 1) {
                json += ",";
            }
		}
		
        json += "]}";
		
		return json;
	}
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		/*
		ArrayList<String> al = Utility.generateDaysOfMonth(2009, 2, Utility.START_FROM_SATURDAY_FLAGS);
		
		for (int index = 0; index < al.size(); index++)
		{	
			System.out.print((String)al.get(index) + " ");
			
			if ((index + 1) % Utility.DAYS_OF_WEEK == 0)
			{
				System.out.println("");
			}
		}
		*/
		
		//System.out.println(generate());
	}

}
